<template>
	<Tabs>
		<TabPane label="运费模板配置">
			<Form ref="form" label-position="top" :model="formData" :rules="rules">
				<FormDescItem label="运费模板名称" prop="name" desc="设置一个运费模板名称，便于区分不同的模板，运费模板名称不能重复">
					<Input v-model="formData.name" />
				</FormDescItem>
				<FormDescItem label="运费计算方式" desc="设置运费的计算方式，可以选择重量或者件数，重量默认单位为 KG">
					<RadioGroup v-model="formData.type">
				        <Radio label="weight">重量</Radio>
				        <Radio label="number">件数</Radio>
				    </RadioGroup>
				</FormDescItem>
			</Form>
			
			<p style="margin-bottom: 10px; font-size: 14px;">运费设置</p>
			<Table :columns="columns" :data="lists">
				<template slot-scope="{ row, index }" slot="title">
					<a href="javascript:;" @click="handleOpenAreaModal(row, index)" :class="{'ui-text-error': !row.district_ids}">{{ !row.district_ids ? '设置配送区域' : '编辑配送区域' }}</a>
					<Poptip title="支持配送区域" :content="handleGetDeliveryArea(row)" transfer placement="right" trigger="hover">
						<Button size="small" style="margin-left: 10px;">查看配送区域</Button>
					</Poptip>
				</template>
				<template slot-scope="{ row, index }" slot="firstValue">
					<InputNumber v-model="lists[index].template.first_value" style="width: 100%;"></InputNumber>
				</template>
				<template slot-scope="{ row, index }" slot="firstFee">
					<InputAmount v-model="lists[index].template.first_fee" :min="0" />
				</template>
				<template slot-scope="{ row, index }" slot="followValue">
					<InputNumber v-model="lists[index].template.follow_value" style="width: 100%;"></InputNumber>
				</template>
				<template slot-scope="{ row, index }" slot="followFree">
					<InputAmount v-model="lists[index].template.follow_fee" :min="0" />
				</template>
				<template slot-scope="{ row, index }" slot="action">
					<Button type="error" size="small" @click="handleDeleteTemplate(index)">删除</Button>
				</template>
			</Table>
			<div class="freight-add" @click="handleAddTemplate">添加配送区域</div>
			<div>
				<Button type="primary" :loading="committing" @click="handleSubmit">保存设置并启用</Button>
				<Button @click="handleBack">返回列表</Button>
			</div>
			
			<DrawerForm
				title="设置配送区域"
				v-model="showModal"
				ok-text="确认选择"
				@on-ok="handleSelectArea"
			>
				<Tree :data="areaListClone" show-checkbox multiple></Tree>
			</DrawerForm>
		</TabPane>
	</Tabs>
</template>

<script>
import Util from '@/libs/util.js';
import FormDescItem from '@/components/form/FormDescItem.vue';
import InputAmount from '@/components/form/InputAmount.vue';
import DrawerForm from '@/components/DrawerForm.vue';
export default {
	name: 'freightConfig',
	components: {
		FormDescItem,
		InputAmount,
		DrawerForm
	},
	data() {
		return {
			committing: false,
			showModal: false,
			currentIndex: 0,
			formData: {
				id: '',
				name: '',
				type: 'weight'
			},
			rules: {
				name: [
					{required: true, message: '请输入运费模板名称', trigger: 'blur'}
				]
			},
			areaList: [],
			areaListClone: [],
			areaFlatList: {},
			lists: [],
			columns: [
				{
					title: '可配送区域',
					slot: 'title',
					width: 215
				},
				{
					title: '首件',
					slot: 'firstValue',
					renderHeader: (h, params) => {
						return h('span', this.formData.type == 'weight' ? '首重（kg）' : '首件');
					}
				},
				{
					title: '运费',
					slot: 'firstFee'
				},
				{
					title: '续件',
					slot: 'followValue',
					renderHeader: (h, params) => {
						return h('span', this.formData.type == 'weight' ? '续重（kg）' : '续件');
					}
				},
				{
					title: '运费',
					slot: 'followFree'
				},
				{
					title: ' ',
					slot: 'action',
					align: 'center',
					width: 80
				}
			]
		}
	},
	computed: {
        areas () {
            return this.$store.state.app.areas;
        },
        deliveryTemplates() {
        	return this.$store.state.app.deliveryTemplates;
        }
    },
	mounted() {
		if(this.$route.query.id) {
			this.formData.id = this.$route.query.id;
			this.init();
		}
		this.handleGetAreaLists(this.areas);
		// 获取运费模板
    	this.$store.dispatch('getDeliveryTemplates');
	},
    watch: {
    	areas: {
    		deep: true,
    		handler(vals) {
    			this.handleGetAreaLists(vals);
    		}
    	}
    },
	methods: {
		init() {
			Util.ajax.post(this.API['API_SETTING_DELIVERY_TEMPLATES_DETAIL'], {id: this.formData.id}).then((res) => {
				this.formData.name = res.name;
				this.formData.type = res.type;
				this.lists = res.delivery_info || [];
				/*this.lists = res.delivery_info.map(item => {
					item.template = {
						first_value: Number(item.template.first_value),
						first_fee: Number(item.template.first_fee),
						follow_value: Number(item.template.follow_value),
						follow_fee: Number(item.template.follow_fee)
					}
					return item;
				});*/
			}).catch(() => {
				
			})
		},
		handleGetAreaLists(areas) {
			if(areas && areas.length > 0) {
				this.areaFlatList = {};
				this.areaList = this.handleFormatArea(areas, 2);
			}else{
				this.areaList = [];
				this.areaFlatList = {};
			}
		},
		handleFormatArea(datas, level) {
			return datas.map(item => {
				let obj = {
					title: item.label,
					value: item.value
				}
				this.areaFlatList[item.value] = item.label;
				if(item.level < level && item.children) {
					obj.children = this.handleFormatArea(item.children, level);
				}
				return obj;
			})
		},
		handleSelectArea() {
			let ids = [];
			function getArea(items) {
				items.forEach(item => {
					if(item.indeterminate) {
						getArea(item.children);
					}else if(item.checked) {
						ids.push(item.value);
					}
				})
			}
			getArea(this.areaListClone);
			this.lists[this.currentIndex].district_ids = ids.join(',');
			this.showModal = false;
		},
		handleAddTemplate() {
			this.lists.push({
				template: {
					first_value: 0,
					first_fee: 0,
					follow_value: 0,
					follow_fee: 0
				},
				district_ids: ''
			})
		},
		// 打开设置地区弹窗
		handleOpenAreaModal(row, index) {
			let ids = row.district_ids ? row.district_ids.split(',') : [];
			const setCheckedArea = function(items) {
				return items.map(item => {
					let obj = {
						title: item.title,
						value: item.value
					}
					if(ids.indexOf(item.value.toString()) >= 0) {
						obj.checked = true;
					}
					if(item.children && item.children.length > 0) {
						obj.children = setCheckedArea(item.children);
					}
					return obj;
				})
			}
			this.areaListClone = setCheckedArea(this.areaList);
			this.currentIndex = index;
			this.showModal = true;
		},
		// 获取配送区域
		handleGetDeliveryArea(row) {
			let ids = row.district_ids.split(',');
			let labels = ids.map(id => {
				return this.areaFlatList[id];
			})
			labels = labels.filter(item => {
				return item;
			})
			return labels.join('、');
		},
		handleDeleteTemplate(index) {
			this.lists.splice(index, 1);
		},
		handleBack() {
			this.$router.back();
		},
		handleSubmit() {
			if(this.committing) return false;
			if(this.formData.id == 1) {
				this.$Message.error('统一运费模板不能修改');
				return false
			}
			// 校验运费规则
			if(this.lists.length == 0) {
				this.$Message.error('请设置运费配送规则');
				return false;
			}
			// 校验配送区域
			let err = this.lists.filter(item => {
				return !item.district_ids;
			})
			if(err.length > 0) {
				this.$Message.error('有未选择配送区域的运费规则');
				return false;
			}
			
			this.$refs.form.validate(valid => {
                if(valid) {
                	let form = this.formData;
                	let params = {
                		name: form.name,
						type: form.type,
						data: this.lists
                	}
                	
                	this.committing = true;
                	
                	if(form.id) {
                		// 编辑
                		params.id = form.id;
	                	Util.ajax.post(this.API['API_SETTING_DELIVERY_TEMPLATES_SAVE'], params).then((res) => {
	                		let templates = this.deliveryTemplates.map(item => {
	                			if(item.id == params.id) {
	                				item.name = res.name;
		                			item.type = res.type;
		                			item.delivery_info = res.delivery_info;
		                			item.update_time = res.update_time;
	                			}
	                			return item;
	                		});
			        		this.$store.commit('setDeliveryTemplates', templates);
			        		
	                		this.$Message.success({
	                			content: '编辑成功',
	                			onClose: () => {
	                				this.handleBack();
	                			}
	                		});
	                	}).catch(() => {
	                		this.committing = false;
	                	})
                	}else{
                		// 创建
                		Util.ajax.post(this.API['API_SETTING_DELIVERY_TEMPLATES_CREATE'], params).then((res) => {
	                		let templates = this.deliveryTemplates;
	                		res.enabled = 1;
	                		res.enabled_text = "已启用";
	                		templates.push(res)
			        		this.$store.commit('setDeliveryTemplates', templates);
	                		this.$Message.success({
	                			content: '创建成功',
	                			onClose: () => {
	                				this.handleBack();
	                			}
	                		});
	                	}).catch(() => {
	                		this.committing = false;
	                	})
                	}
                }
            });
		}
	}
}
</script>

<style>
.freight-add {
	margin-bottom: 20px;
	border: 1px solid #dcdee2;
	border-top: 0;
	text-align: center;
	line-height: 49px;
	background-color: #f8f8f9;
	cursor: pointer;
}
</style>